package cn.edu.abtu.config.security.filter;

import cn.edu.abtu.config.redis.RedisService;
import cn.edu.abtu.config.security.exception.CustomerAuthenticationException;
import cn.edu.abtu.config.security.handler.LoginFailureHandler;
import cn.edu.abtu.config.security.service.CustomerUserDetailsService;
import cn.edu.abtu.utils.JwtUtils;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/*
* token过滤器
* */
@Data
@Component
public class CheckTokenFilter extends OncePerRequestFilter {

    /*
     * 获取登录地址
     * */
    @Value("${request.login.url}")
    private String loginUrl;

    @Resource
    private RedisService redisService;

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private CustomerUserDetailsService customerUserDetailsService;

    @Resource
    private LoginFailureHandler loginFailureHandler;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            // 获取当前请求的URI
            String requestURI = request.getRequestURI();
            // 如果当前请求不是登录请求,则需要token验证
            if (!requestURI.equals(loginUrl)) {
                this.validateToken(request);
            }
        }catch (AuthenticationException exception){
            // 认证失败
            loginFailureHandler.onAuthenticationFailure(request,response,exception);
        }
        // 登录请求不需要token验证
        doFilter(request, response, filterChain);
    }

    private void validateToken(HttpServletRequest request) throws AuthenticationException {
        // 从请求头中未获取到token信息
        String token = request.getHeader("token");
        // 如果从请求头中未获取到token信息,则从请求参数中看是否有token信息
        if (Objects.isNull(token)) {
            token = request.getParameter("token"); //从请求参数中看是否有token信息
        }
        // 如果两种情况都没有获取到token,则抛出异常
        if (Objects.isNull(token)) {
            throw new CustomerAuthenticationException("token不存在");
        }
        //判断redis中是否存在该token
        String tokenKey = "token_" + token;
        String redisToken = redisService.get(tokenKey);
        //如果redis里面没有token,说明该token失效
        if (Objects.isNull(redisToken)) {
            throw new CustomerAuthenticationException("token已过期");
        }
        //如果token和Redis中的token不一致，则验证失败
        if (!token.equals(redisToken)) {
            throw new CustomerAuthenticationException("token验证失败");
        }
        // 如果存在token,则从token中解析用户名
        String username = jwtUtils.getUsernameFromToken(token);
        // 如果用户名为空,则解析失败
        if (Objects.isNull(username)){
            throw new CustomerAuthenticationException("token解析失败");
        }
        // 获取用户信息
        UserDetails userDetails = customerUserDetailsService.loadUserByUsername(username);
        if (Objects.isNull(userDetails)){
            throw new CustomerAuthenticationException("token验证失败");
        }
        // 创建用户身份认证对象 UsernamePasswordAuthenticationToken(用户信息, 密码, 权限)
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        // 设置请求信息
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        // 将认证的信息交给 Spring Security上下文
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    }
}
